package com.example.demo.controller.admin;


import com.example.demo.entity.Store;
import com.example.demo.entity.User;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.StoreService;
import com.example.demo.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin/store")
@RequiresPermissions("store-manage")
public class AdminStoreController {


    @Autowired
    private StoreService storeService;

    @Autowired
    private UserService userService;

    @Value("${business.role-id}")
    private String roleId;


    @RequestMapping("/list")
    public String storeList(Model model){

        List<Store> stores=storeService.findAllStores();

        for(Store store:stores){
            User user=userService.findUserById(store.getStoreManagerId());
            store.setStoreManagerName(user.getUsername());
        }

        model.addAttribute("stores",stores);

        return "/admin/store/list";

    }

    @RequestMapping("/toAddition")
    public String storeToAddtion(Model model){


        List<User> users=userService.findUserByRoleId(Integer.parseInt(roleId));
        model.addAttribute("users",users);

        return "/admin/store/add";
    }


    @RequestMapping("/{storeId}")
    public String getStore(@PathVariable("storeId")Integer storeId,Model model){

        Store store=storeService.findStoreById(storeId);

        User user=userService.findUserById(store.getStoreManagerId());




        String userName=user.getUsername();
        store.setStoreManagerName(userName);
        model.addAttribute("store",store);

        return "/admin/store/edit";
    }

    @RequestMapping("/addition")
    public String addStore(Store store){
       storeService.addStore(store);
        return "forward:list";
    }

    @RequestMapping("/deletion/{storeId}")
    public String delete(@PathVariable(value = "storeId")Integer storeId){

        storeService.delStoreById(storeId);
        return "forward:/admin/store/list";
    }

    @RequestMapping("/edit")
    public String updateStore(Store store,Model model){

        BSResult bsResult=storeService.updateStore(store);
        if(bsResult.getCode()==200)
        model.addAttribute("saveMsg",bsResult.getMessage());
        return "forward:/admin/store/"+store.getStoreId();

    }


}
